import cgi
import os
import datetime
import time
import logging
import urllib
import xml.dom.minidom
import random

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

from datamodel import GeoEvent

class mainPage(webapp.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    f = open(path)
    doc = f.read()
    f.close()
    self.response.out.write(doc)

class myRequest(webapp.RequestHandler):
  def get(self):
      geoevents = db.GqlQuery("SELECT * FROM GeoEvent ORDER BY user ASC LIMIT 10")
      allusers = ""
      for geoevent in geoevents:
        allusers = allusers + " %s" % geoevent.user
      self.response.out.write(allusers)

class sendKml(webapp.RequestHandler):
      def get(self):
        latitude = random.randrange(-90, 90)
        longitude = random.randrange(-180, 180)
        kml = (
           '<?xml version="1.0" encoding="UTF-8"?>\n'
           '<kml xmlns="http://www.opengis.net/kml/2.2">\n'
           '<Placemark>\n'
           '<name>Random Placemark</name>\n'
           '<Point>\n'
           '<coordinates>%d,%d</coordinates>\n'
           '</Point>\n'
           '</Placemark>\n'
           '</kml>'
           ) %(longitude, latitude)
        self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
        self.response.out.write(kml)      
      
class postGeodata(webapp.RequestHandler):
  def post(self):
    geoevent = GeoEvent()
    geoevent.contents = self.request.get('contents')
    geoevent.user = self.request.get('user')
    geoevent.put()
    self.redirect('/')
    
class jsonOutput(webapp.RequestHandler): 
      def get(self):
          geoJson = (
                        '['
                           '{ "animal" : "Cat",  "message" : "Meow"  },'
                           '{ "animal" : "Dog",  "message" : "Woof"  },'
                           '{ "animal" : "Cow",  "message" : "Moo"   },'
                           '{ "animal" : "Duck", "message" : "Quack" },'
                           '{ "animal" : "Lion", "message" : "Roar"  }'
                        ']'
                    )
          self.response.headers['Content-Type'] = 'text/javascript'
          self.response.out.write(geoJson) 
   
    
application = webapp.WSGIApplication(
                                     [('/', mainPage),
                                      ('/sign', myRequest),
                                      ('/postdata', postGeodata),
                                      ('/getxml', sendKml),
                                      ('/getjson', jsonOutput)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
